# -*- encoding:utf-8 -*-
# @time:2023-04-23 23:34
# @Author : serein
# @Email: serein@qq.com
# @File:serializers.py
# @Software: PyCharm
import re

from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from address.models import area,Address

class AddressSerializers(ModelSerializer):
    # 这个是展示的时候出现的，让我们能看清楚地址的名字而不是id
    province_name = serializers.CharField(source='province.name',read_only=True)
    city_name = serializers.CharField(source="city.name",read_only=True)
    district_name = serializers.CharField(source="district.name",read_only=True)
    user_name = serializers.CharField(source="user.name",read_only=True)
    class Meta:
        model = Address
        exclude = ['is_delete']
    #额外在序列化器对字段添加判别的时候，需要用validata_加上需要判别的字段
    def validate_phone(self, value):
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号码格式错误')
        return value

class AreaSerializer(ModelSerializer):
    """行政区划自身序列化器"""
    class Meta:
        model = area
        fields = ['id', 'name']

class ParentSerializer(ModelSerializer):
    """行政区划自身序列化器及子级区划"""
    area_set = AreaSerializer(many=True, read_only=True)

    class Meta:
        model = area
        fields = ['id', 'name', 'area_set']
